var mongoose = require('mongoose')
var fs = require('fs')
mongoose.connect('mongodb://localhost/test', {
  useUnifiedTopology: true,
  useNewUrlParser: true
})
var db = mongoose.connection

db.on('err', console.error.bind(console, 'connection err:'))
db.once('open', () => {
  console.log('mongo connected')
})
var loginSchema = new mongoose.Schema({
  id: String,
  username: String,
  password: String
})

var blogListSchema = new mongoose.Schema({
  title: String,
  kind: String,
  id: String,
  content: String
})

var login = db.model(login, loginSchema, 'login')
var blogList = db.model(blogList, blogListSchema, 'blogList')

async function queryMaxIDLogin() {
  let temp = 0
  // 按照id排序，然后取第一条
  await login.find({}).sort({
    'id': -1
  }).limit(1).then(function (doc) {
    if (doc.length > 0) {
      temp = Number(doc[0].id)
    } else {
      console.log('Login collection is empty!')
    }
  })
  return temp
}
// 注册
exports.register = async function (username, password) {
  return new Promise(async (resolve, reject) => {
    const arr = await login.find({
      username
    })
    console.log('arr___________', arr)
    let value = await queryMaxIDLogin()
    if (arr.length) {
      console.log('already register')
      resolve(false)
    } else {
      var query = new login({
        username,
        password,
        id: ++value
      })
      query.save(err => {
        if (err) {
          console.log(err)
          resolve(false)
        }
        console.log('register done')
        resolve(true)
      })

    }
  })


}

// 校验是否是合法用户
exports.valiateUser = async function (username, password) {
  let results = await login.find({
    username
  })
  return Boolean(results[0] && results[0].password === password)
}
// 存储用户


// 查询某个分类下的全部文章
exports.getBlogList = async function (kind) {
  let query = {}
  let results = []
  if (kind !== '/') {
    query = {
      kind
    }
  }
  results = await blogList.find(query)
  return results
}

// 文件上传

// 查找ID的最大值
async function queryMaxID() {
  let temp = 0
  // 按照id排序，然后取第一条
  await blogList.find({}).sort({
    'id': -1
  }).limit(1).then(function (doc) {
    if (doc.length > 0) {
      temp = Number(doc[0].id)
    } else {
      console.log('collection is empty!')
    }
  })
  return temp
}

// 添加一条数据至mongodb
exports.insertBlogList = async function (path, title, kind) {
  var content = await fs.readFileSync(path, {
    encoding: 'UTF-8'
  })
  let value = await queryMaxID()
  var record = new blogList({
    title: title,
    kind,
    id: ++value,
    content: content
  })
  record.save(err => {
    if (err) {
      console.log(err)
      return
    }
    console.log('Insert done')
  })
}

// 删除或者修改博客的分类
function deleteBlogId(id) {
  let query = {
    id: id
  }
  blogList.remove(query).then(doc => {
    console.log('done')
  })
}

function modifyBlogKind(id, kind) {
  let query = {
    id: id
  }
  blogList.findOneAndUpdate(query, {
    kind: kind
  }).then(doc => console.log('done'))
}


// 文章内容读取
exports.readBlog = async function (id) {
  var result = await blogList.find({
    id
  })
  // var title =  await blog.find({id})
  return result[0]
}